extends Window

# 自动售卖设置窗口
# 用于配置自动售卖的等级和品质条件

# PlayerHUD引用，用于获取正确的界面尺寸
var player_hud: Control = null

# UI节点引用
@onready var enable_checkbox = $VBoxContainer/EnableContainer/EnableCheckBox
@onready var level_spinbox = $VBoxContainer/LevelContainer/LevelHBox/LevelSpinBox
@onready var common_checkbox = $VBoxContainer/QualityContainer/QualityVBox/CommonCheckBox
@onready var uncommon_checkbox = $VBoxContainer/QualityContainer/QualityVBox/UncommonCheckBox
@onready var rare_checkbox = $VBoxContainer/QualityContainer/QualityVBox/RareCheckBox
@onready var epic_checkbox = $VBoxContainer/QualityContainer/QualityVBox/EpicCheckBox
@onready var legendary_checkbox = $VBoxContainer/QualityContainer/QualityVBox/LegendaryCheckBox
@onready var save_button = $VBoxContainer/ButtonContainer/SaveButton
@onready var cancel_button = $VBoxContainer/ButtonContainer/CancelButton

# 自动售卖设置数据
var auto_sell_settings = {
	"enabled": false,
	"max_level": 1,
	"qualities": {
		"COMMON": false,
		"UNCOMMON": false,
		"RARE": false,
		"EPIC": false,
		"LEGENDARY": false
	}
}

# 设置文件路径
const SETTINGS_FILE_PATH = "user://auto_sell_settings.json"

func _ready():
	"""初始化窗口"""
	# 设置窗口属性
	_setup_window()
	
	# 连接按钮信号
	save_button.pressed.connect(_on_save_pressed)
	cancel_button.pressed.connect(_on_cancel_pressed)
	
	# 连接窗口关闭信号
	close_requested.connect(_on_close_requested)
	
	# 加载设置
	_load_settings()
	
	# 更新UI
	_update_ui()
	
	# 默认隐藏窗口
	hide()

func _setup_window():
	"""设置窗口属性"""
	title = "自动售卖设置"
	
	# 设置最小尺寸限制
	var min_width = 400
	var min_height = 300
	min_size = Vector2(min_width, min_height)
	
	unresizable = false
	always_on_top = true

func _setup_window_size():
	"""动态设置窗口大小"""
	# 获取PlayerHUD大小
	var player_hud_size = player_hud.size if player_hud else get_viewport().get_visible_rect().size
	
	# 设置窗口大小为PlayerHUD大小的一部分（比背包小一些）
	var window_width = int(player_hud_size.x * 0.4)  # 40%宽度
	var window_height = int(player_hud_size.y * 0.6)  # 60%高度
	size = Vector2i(window_width, window_height)
	
	# 居中显示
	position = Vector2i(
		int((player_hud_size.x - window_width) / 2),
		int((player_hud_size.y - window_height) / 2 + 35)
	)

func _load_settings():
	"""从文件加载设置"""
	if FileAccess.file_exists(SETTINGS_FILE_PATH):
		var file = FileAccess.open(SETTINGS_FILE_PATH, FileAccess.READ)
		if file:
			var json_string = file.get_as_text()
			file.close()
			
			var json = JSON.new()
			var parse_result = json.parse(json_string)
			if parse_result == OK:
				auto_sell_settings = json.data
				print("自动售卖设置已加载")
			else:
				print("自动售卖设置文件解析失败")
		else:
			print("无法打开自动售卖设置文件")
	else:
		print("自动售卖设置文件不存在，使用默认设置")

func _save_settings():
	"""保存设置到文件"""
	var file = FileAccess.open(SETTINGS_FILE_PATH, FileAccess.WRITE)
	if file:
		var json_string = JSON.stringify(auto_sell_settings)
		file.store_string(json_string)
		file.close()
		print("自动售卖设置已保存")
	else:
		print("无法保存自动售卖设置")

func _update_ui():
	"""根据设置更新UI"""
	enable_checkbox.button_pressed = auto_sell_settings.enabled
	level_spinbox.value = auto_sell_settings.max_level
	
	common_checkbox.button_pressed = auto_sell_settings.qualities.COMMON
	uncommon_checkbox.button_pressed = auto_sell_settings.qualities.UNCOMMON
	rare_checkbox.button_pressed = auto_sell_settings.qualities.RARE
	epic_checkbox.button_pressed = auto_sell_settings.qualities.EPIC
	legendary_checkbox.button_pressed = auto_sell_settings.qualities.LEGENDARY

func _update_settings_from_ui():
	"""从UI更新设置"""
	auto_sell_settings.enabled = enable_checkbox.button_pressed
	auto_sell_settings.max_level = int(level_spinbox.value)
	
	auto_sell_settings.qualities.COMMON = common_checkbox.button_pressed
	auto_sell_settings.qualities.UNCOMMON = uncommon_checkbox.button_pressed
	auto_sell_settings.qualities.RARE = rare_checkbox.button_pressed
	auto_sell_settings.qualities.EPIC = epic_checkbox.button_pressed
	auto_sell_settings.qualities.LEGENDARY = legendary_checkbox.button_pressed

func _on_save_pressed():
	"""保存按钮点击处理"""
	_update_settings_from_ui()
	_save_settings()
	
	# 通知AutoSellManager更新设置
	if AutoSellManager:
		AutoSellManager.update_settings(auto_sell_settings)
	
	print("自动售卖设置已保存并应用")
	hide()

func _on_cancel_pressed():
	"""取消按钮点击处理"""
	# 恢复UI到当前设置
	_update_ui()
	hide()

func _on_close_requested():
	"""窗口关闭请求处理"""
	_on_cancel_pressed()

func toggle_visibility():
	"""切换窗口可见性"""
	if visible:
		hide()
	else:
		show()
		# 重新加载设置以确保显示最新数据
		_load_settings()
		_update_ui()
		# 设置窗口大小和位置
		_setup_window_size()

func get_auto_sell_settings():
	"""获取当前自动售卖设置"""
	return auto_sell_settings

func should_auto_sell_item(item_data):
	"""检查物品是否应该自动售卖"""
	# 如果自动售卖未启用，返回false
	if not auto_sell_settings.enabled:
		return false
	
	# 检查物品类型（仅限装备）
	if not item_data.has("slot"):
		return false
	
	# 检查等级条件
	var item_level = item_data.get("level_requirement", 1)
	if item_level > auto_sell_settings.max_level:
		return false
	
	# 检查品质条件
	var item_rarity = item_data.get("rarity", "COMMON")
	if not auto_sell_settings.qualities.has(item_rarity):
		return false
	
	return auto_sell_settings.qualities[item_rarity]